package com.cx.file;

import cn.hutool.core.util.StrUtil;
import com.cx.file.config.FileManageConfigProperties;
import com.cx.file.exception.FileManageException;
import com.cx.file.service.FileManageService;
import com.cx.file.service.impl.FileManageServiceImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author cx
 * @description: 自动配置启动类
 * @date 2023/6/2 17:09
 */
@Configuration
@ConditionalOnClass(FileManageService.class)
@EnableConfigurationProperties(FileManageConfigProperties.class)
public class FileManageAutoConfiguration {
    private final FileManageConfigProperties properties;

    public FileManageAutoConfiguration(FileManageConfigProperties properties) throws IOException {
        configCheck(properties);
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    public FileManageService exampleService() {
        return new FileManageServiceImpl(properties);
    }

    private void configCheck(FileManageConfigProperties properties) throws IOException {
        String path = properties.getPath();
        if (StrUtil.isBlank(path)) {
            throw new FileManageException("file.path配置不能为空");
        }
        Path rootLocation = Paths.get(path);
        if (!Files.exists(rootLocation)) {
            Files.createDirectories(rootLocation);
        }
    }
}
